<template>
  <div class="form__container">
    <FormTitle>国内主体-工商信息</FormTitle>
    <t-form ref="chinaIacRef" :rules="pageData.formRules" :disabled="props.readOnly" :data="pageData.localData">
      <t-space direction="vertical" style="width: 100%" size="large">
        <t-row justify="space-around">
          <t-col :span="6">
            <t-form-item :labelWidth="120" label="企业代码" name="creditCode">
              <t-input
                v-if="!readOnly"
                v-model="pageData.localData.creditCode"
                placeholder="输入统一社会信用代码"
                maxlength="100"
              />
              <div v-else class="form__text">{{ pageData.localData.creditCode }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="120" label="法人代表" name="legalPerson">
              <t-input
                :showLimitNumber="true"
                v-if="!readOnly"
                v-model="pageData.localData.legalPerson"
                maxlength="100"
              />
              <div v-else class="form__text">{{ pageData.localData.legalPerson }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row justify="space-around">
          <t-col :span="6">
            <t-form-item :labelWidth="120" label="名称" name="registerName">
              <t-input
                :showLimitNumber="true"
                v-if="!readOnly"
                v-model="pageData.localData.registerName"
                maxlength="100"
              />
              <div v-else class="form__text">{{ pageData.localData.registerName }}</div>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="120" label="类型" name="type">
              <t-input :showLimitNumber="true" v-if="!readOnly" v-model="pageData.localData.type" maxlength="100" />
              <div v-else class="form__text">{{ pageData.localData.type }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row justify="space-around">
          <t-col :span="6">
            <t-form-item :labelWidth="120" label="成立日期" name="registerTime">
              <t-date-picker v-model="pageData.localData.registerTime" style="width: 100%" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :labelWidth="120" label="营业期限" name="registerLimitTime">
              <t-date-range-picker v-model="pageData.localData.registerLimitTime" style="width: 100%" />
            </t-form-item>
          </t-col>
        </t-row>
        <t-row justify="space-around">
          <t-col :span="12">
            <t-form-item :labelWidth="120" label="注册资本" name="registerMoney">
              <t-input
                :showLimitNumber="true"
                v-if="!readOnly"
                v-model="pageData.localData.registerMoney"
                maxlength="100"
              />
              <div v-else class="form__text">{{ pageData.localData.registerMoney }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row justify="space-around">
          <t-col :span="12">
            <t-form-item :labelWidth="120" label="住所" name="registerAddress">
              <t-input
                :showLimitNumber="true"
                v-if="!readOnly"
                v-model="pageData.localData.registerAddress"
                maxlength="100"
              />
              <div v-else class="form__text">{{ pageData.localData.registerAddress }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row justify="space-around">
          <t-col :span="12">
            <t-form-item :labelWidth="120" label="经营范围" name="registerBusiness">
              <t-textarea v-if="!readOnly" v-model="pageData.localData.registerBusiness" :autosize="{ minRows: 5 }" />
              <div v-else class="form__text">{{ pageData.localData.registerBusiness }}</div>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row justify="space-around">
          <t-col :span="12">
            <t-form-item :labelWidth="120" label="执照扫描件" help="仅允许上传一个">
              <t-upload
                theme="file-flow"
                :withCredentials="true"
                :auto-upload="true"
                :multiple="false"
                :request-method="handleFileUpload"
                v-model:files="pageData.fileList"
                @remove="handleUploadRemove"
                :max="1"
              />
            </t-form-item>
          </t-col>
        </t-row>
      </t-space>
    </t-form>
  </div>
</template>

<script setup lang="ts">
import { uploadFileMany } from "@/api/file";
import { reactive, ref, watch } from "vue";

import FormTitle from "@/components/Form/Title/index.vue";
import type { FormInstanceFunctions } from "tdesign-vue-next";

const props = defineProps(["formData", "readOnly"]);
const emits = defineEmits(["updateData", "onValidateResult"]);

const chinaIacRef = ref<FormInstanceFunctions | null>(null);

const pageData = reactive({
  formRules: {
    legalPerson: [{ required: true, message: "请输入法人", type: "error", trigger: "blur" }],
    registerTime: [{ required: true, message: "请输入成立日期", type: "error", trigger: "blur" }],
    registerTimeLimit: [{ required: true, message: "请输入营业期限", type: "error", trigger: "blur" }],
    registerName: [{ required: true, message: "请输入名称", type: "error", trigger: "blur" }],
    registerAddress: [{ required: true, message: "请输入住所", type: "error", trigger: "blur" }],
    type: [{ required: true, message: "请输入类型", type: "error", trigger: "blur" }],
    creditCode: [{ required: true, message: "请输入统一社会信用代码", type: "error", trigger: "blur" }],
    registerMoney: [{ required: true, message: "请输入注册资本", type: "error", trigger: "blur" }]
  },
  localData: { ...props.formData },
  fileList: [] as Record<string, any>[]
});

const initFormData = () => {
  // console.log(pageData.localData);
  if (pageData.localData.registerLicenseId !== "" && pageData.localData.registerLicenseId !== null) {
    pageData.fileList = [
      {
        name: pageData.localData.registerLicense.name,
        url: `/api/upload/${pageData.localData.registerLicense.fileURI}`,
        size: pageData.localData.registerLicense.size,
        status: "success"
      }
    ];
  }
};

const handleFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      pageData.localData.registerLicenseId = res.data[0].id;
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleUploadRemove = () => {
  pageData.localData.registerLicenseId = "";
  pageData.fileList = [];
};

const getFormValidateResult = async () => {
  return await chinaIacRef?.value?.validateOnly();
};

watch(
  () => pageData.localData,
  (newData) => {
    const emitData = {
      ...newData,
      registerLimitTimeStart: pageData.localData.registerLimitTime[0],
      registerLimitTimeEnd: pageData.localData.registerLimitTime[1]
    };
    emits("updateData", emitData);
    emits("onValidateResult", getFormValidateResult());
  },
  { deep: true, flush: "post" }
);

// pageData.localData = { ...props.formData };
initFormData();
</script>
